package cn.tedu.charging.order.rabbit;

import cn.tedu.charging.order.config.RabbitMQConfiguration;
import cn.tedu.common.pojo.po.DeviceMQPO;
import cn.tedu.charging.order.pojo.po.OrderMQPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RabbitMQProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     * @param orderMQPO
     */
    public void send(OrderMQPO orderMQPO){
        //channel.basicPublish(exchangeName, routingKey, null, messageBytes);
        //rabbitTemplate.convertAndSend 方法返回值是 void ，无法知道是否发送成功
        //需要RabbitMQ 收到 订单发送的消息 后 告诉订单 说 消息我收到了

        //设置RabbitMQ的确认机制的回调类,保证消息发送的时候不丢
        rabbitTemplate.setConfirmCallback((data, ack, cause)->{
            log.info("生产者发送消息回调，消息是否发送成功data:{},ack:{},cause:{},",data,ack,cause);
            if (ack) {
                log.debug("RabbitMQ 收到消息 生产者发送消息成功:{}",orderMQPO);
            }else{
                log.debug("RabbitMQ 没有收到消息，打日志，进行重试，重新发送,重新发送几次后还是不行，告警,告警 告警");
                log.debug("生产者发送消息失败:{},原因:{}",orderMQPO,cause);
            }
        });
        rabbitTemplate.convertAndSend(RabbitMQConfiguration.EXCHANGE_NAME,
                RabbitMQConfiguration.ROUTING_KEY,orderMQPO);
        log.info("生产者发送消息:{}",orderMQPO);
    }

    /**
     * 发送消息
     * @param deviceMQPO
     */
    public void sendToDevice(DeviceMQPO deviceMQPO){
        log.info("生产者给设备发送消息:{}",deviceMQPO);
        rabbitTemplate.convertAndSend(RabbitMQConfiguration.DEVICE_EXCHANGE_NAME,
                RabbitMQConfiguration.DEVICE_ROUTING_KEY,deviceMQPO);
        log.info("生产者给设备发送消息成功:{}",deviceMQPO);
    }


    public void sendMessage(String json){
        log.info("生产者给设备发送消息:{}",json);
        //设置RabbitMQ的确认机制的回调类,保证消息发送的时候不丢
       /* rabbitTemplate.setConfirmCallback((correlationData, ack, cause)->{
            log.info("生产者发送消息回调，消息是否发送成功:{},cause:{}",ack,cause);
            if (ack) {
                log.info("生产者发送消息成功:{}",json);
            }else{
                log.info("生产者发送消息失败:{}",json);
            }
        });*/
        rabbitTemplate.convertAndSend(RabbitMQConfiguration.DEVICE_EXCHANGE_NAME,
                RabbitMQConfiguration.DEVICE_ROUTING_KEY,json);
        log.info("生产者给设备发送消息成功:{}",json);
    }
}
